/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UIBaoCao.java
 *
 * Created on Jun 14, 2011, 9:00:05 AM
 */
package Implementation.SourceCode.GUI;

import Implementation.SourceCode.BLL.WriteExcel;
import Implementation.SourceCode.DAL.DB_Access;
import Implementation.SourceCode.Utilities.Utilities;
import Implementation.SourceCode.entities.diengiai;
import java.awt.BorderLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

/**
 *
 * @author mrkingdom75
 */
public class UIBaoCao extends javax.swing.JFrame {

    private DB_Access db;
    private HashMap<Integer, String> lstThuTu;

    /** Creates new form UIBaoCao */
    public UIBaoCao() {
        setTitle("Báo Cáo Chi - Báo Cáo - © mrkingdom75@gmail.com");
        initComponents();
        buttonGroup1.add(rdbOn);
        buttonGroup1.add(rdbFrom);
        db = new DB_Access();
        txtDuongDan.setEditable(false);
        txtDuongDan.setText("D:\\");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        panNorth = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        panWest = new javax.swing.JPanel();
        panEast = new javax.swing.JPanel();
        panSouth = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        panCenter = new javax.swing.JPanel();
        dateOn = new com.toedter.calendar.JDateChooser();
        dateFrom = new com.toedter.calendar.JDateChooser();
        rdbOn = new javax.swing.JRadioButton();
        rdbFrom = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        dateTo = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        txtDuongDan = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        cbxThang = new javax.swing.JComboBox();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panNorth.setBackground(new java.awt.Color(0, 102, 0));
        panNorth.setPreferredSize(new java.awt.Dimension(400, 80));
        panNorth.setLayout(new java.awt.BorderLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Báo Cáo");
        panNorth.add(jLabel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(panNorth, java.awt.BorderLayout.NORTH);

        panWest.setBackground(new java.awt.Color(0, 102, 0));
        panWest.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panWestLayout = new javax.swing.GroupLayout(panWest);
        panWest.setLayout(panWestLayout);
        panWestLayout.setHorizontalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panWestLayout.setVerticalGroup(
            panWestLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 393, Short.MAX_VALUE)
        );

        getContentPane().add(panWest, java.awt.BorderLayout.WEST);

        panEast.setBackground(new java.awt.Color(0, 102, 0));
        panEast.setPreferredSize(new java.awt.Dimension(20, 200));

        javax.swing.GroupLayout panEastLayout = new javax.swing.GroupLayout(panEast);
        panEast.setLayout(panEastLayout);
        panEastLayout.setHorizontalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );
        panEastLayout.setVerticalGroup(
            panEastLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 393, Short.MAX_VALUE)
        );

        getContentPane().add(panEast, java.awt.BorderLayout.EAST);

        panSouth.setBackground(new java.awt.Color(0, 102, 0));
        panSouth.setPreferredSize(new java.awt.Dimension(400, 70));

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 36));
        jButton1.setText("Ghi");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 36));
        jButton2.setText("Đóng");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panSouthLayout = new javax.swing.GroupLayout(panSouth);
        panSouth.setLayout(panSouthLayout);
        panSouthLayout.setHorizontalGroup(
            panSouthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panSouthLayout.createSequentialGroup()
                .addContainerGap(673, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );
        panSouthLayout.setVerticalGroup(
            panSouthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panSouthLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panSouthLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(panSouth, java.awt.BorderLayout.SOUTH);

        panCenter.setBackground(new java.awt.Color(255, 255, 255));

        dateOn.setDateFormatString("dd-MM-yyyy");
        dateOn.setFont(new java.awt.Font("Tahoma", 0, 30));

        dateFrom.setDateFormatString("dd-MM-yyyy");
        dateFrom.setFont(new java.awt.Font("Tahoma", 0, 30));

        rdbOn.setBackground(new java.awt.Color(255, 255, 255));
        rdbOn.setFont(new java.awt.Font("Tahoma", 0, 36));
        rdbOn.setText("Ngày");

        rdbFrom.setBackground(new java.awt.Color(255, 255, 255));
        rdbFrom.setFont(new java.awt.Font("Tahoma", 0, 36));
        rdbFrom.setText("Từ Ngày");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36));
        jLabel2.setText("Đến Ngày");

        dateTo.setDateFormatString("dd-MM-yyyy");
        dateTo.setFont(new java.awt.Font("Tahoma", 0, 30));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel3.setText("Đường Dẫn:");

        txtDuongDan.setFont(new java.awt.Font("Tahoma", 0, 36));

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton3.setText("Tìm");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel4.setText("Xóa dữ liệu tháng : ");

        cbxThang.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        cbxThang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12", " " }));

        jButton4.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton4.setText("Xóa");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panCenterLayout = new javax.swing.GroupLayout(panCenter);
        panCenter.setLayout(panCenterLayout);
        panCenterLayout.setHorizontalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCenterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rdbOn)
                            .addComponent(rdbFrom))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(dateFrom, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                            .addComponent(dateOn, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))
                        .addGap(22, 22, 22)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateTo, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(txtDuongDan, javax.swing.GroupLayout.PREFERRED_SIZE, 523, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3))
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbxThang, 0, 395, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton4)))
                .addContainerGap())
        );
        panCenterLayout.setVerticalGroup(
            panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panCenterLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addGroup(panCenterLayout.createSequentialGroup()
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(dateOn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(rdbOn))
                        .addGap(18, 18, 18)
                        .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(dateTo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dateFrom, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(rdbFrom, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addGap(18, 18, 18)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDuongDan, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addGroup(panCenterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbxThang, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addContainerGap(105, Short.MAX_VALUE))
        );

        getContentPane().add(panCenter, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if (validateInput()) {
                if (rdbOn.isSelected()) {
                    int ngayOn = dateOn.getCalendar().get(Calendar.DAY_OF_MONTH);
                    int thangOn = dateOn.getCalendar().get(Calendar.MONTH) + 1;
                    Vector<diengiai> lstDienGiai = db.getDataOn(ngayOn, thangOn);
                    if (lstDienGiai.size() > 0) {

                        //lstThuTu = getLstThuTu(lstDienGiai);
                        dalg = new JDialog();
                        WriteExcel we = new WriteExcel(dalg);
                        we.setFileName(txtDuongDan.getText());
                        we.setLstDienGiai(lstDienGiai);
                        we.setNgay(ngayOn);
                        we.setThang(thangOn);
                        we.start();
                        // chạy progress bar
                        loadProgressBar();
                    } else {
                        JOptionPane.showMessageDialog(this, "Không có hàng để ghi file");
                    }
                } else {
                    int ngayFrom = dateFrom.getCalendar().get(Calendar.DAY_OF_MONTH);
                    int thangFrom = dateFrom.getCalendar().get(Calendar.MONTH) + 1;
                    int ngayTo = dateTo.getCalendar().get(Calendar.DAY_OF_MONTH);
                    int thangTo = dateTo.getCalendar().get(Calendar.MONTH) + 1;
                    Vector<diengiai> lstDienGiai = db.getDataFromTo(ngayFrom, thangFrom, ngayTo, thangTo);
                    if (lstDienGiai.size() > 0) {
                        //lstThuTu = getLstThuTu(lstDienGiai);
                        dalg = new JDialog();
                        WriteExcel we = new WriteExcel(dalg);
                        we.setFileName(txtDuongDan.getText());
                        we.setLstDienGiai(lstDienGiai);
                        we.setNgay(ngayTo);
                        we.setThang(thangTo);
                        we.start();
                        // chạy progress bar
                        loadProgressBar();
                    } else {
                        JOptionPane.showMessageDialog(this, "Không có hàng để ghi file");
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    private JDialog dalg;

    private void loadProgressBar() {

        dalg.setTitle("Xin chờ");
        dalg.setModal(true);
        JProgressBar progress = new JProgressBar();
        dalg.setUndecorated(true);
        progress.setString("Đang ghi file");
        progress.setIndeterminate(true);
        progress.setStringPainted(true);
        dalg.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        dalg.setSize(200, 25);
        dalg.getContentPane().setLayout(new BorderLayout());
        dalg.getContentPane().add(progress);
        Utilities.centerForm(dalg);
        dalg.show();
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Tìm Đường Dẫn");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //
        // disable the "All files" option.
        //
        chooser.setAcceptAllFileFilterUsed(false);
        //
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            txtDuongDan.setText(chooser.getSelectedFile() + "");
        } else {
            txtDuongDan.setText("abc");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        try {
            int thang = cbxThang.getSelectedIndex() + 1;
            if (JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn muốn xóa dữ liệu tháng " + thang) == JOptionPane.YES_OPTION) {
                // back up before delete
                String backUpFolderName = "backup/backup database/"+getDateTime();
                File folderBackup = new File(backUpFolderName);
                if(!folderBackup.exists()){
                    folderBackup.mkdir();
                }
                String fileGoc = "Database/baocao.db";
                String fileBackup = backUpFolderName+"/baocao.db";
                copyFile(fileGoc,fileBackup);
                // xóa tháng
                if (db.deleteDataByMonth(thang) > 1) {
                    JOptionPane.showMessageDialog(this, "Dữ liệu của tháng " + thang + " đã được xóa thành công!!!");
                } else {
                    JOptionPane.showMessageDialog(this, "Không xóa được dữ liệu. Có lỗi xảy ra!!!");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UIBaoCao().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cbxThang;
    private com.toedter.calendar.JDateChooser dateFrom;
    private com.toedter.calendar.JDateChooser dateOn;
    private com.toedter.calendar.JDateChooser dateTo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel panCenter;
    private javax.swing.JPanel panEast;
    private javax.swing.JPanel panNorth;
    private javax.swing.JPanel panSouth;
    private javax.swing.JPanel panWest;
    private javax.swing.JRadioButton rdbFrom;
    private javax.swing.JRadioButton rdbOn;
    private javax.swing.JTextField txtDuongDan;
    // End of variables declaration//GEN-END:variables

    private boolean validateInput() throws Exception {
        boolean retVat = false;
        try {
            if (!rdbOn.isSelected() && !rdbFrom.isSelected()) {
                JOptionPane.showMessageDialog(this, "Bạn chưa chọn ngày");
                retVat = false;
            } else {
                if (rdbFrom.isSelected()) {
                    if (dateFrom.getDate().after(dateTo.getDate())) {
                        JOptionPane.showMessageDialog(this, "Phải nhập ngày sau lớn hơn ngày trước");
                        return false;
                    }
                }
                if (txtDuongDan.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(this, "Đường Dẫn chưa nhập");
                    return false;
                }
                retVat = true;
            }
        } catch (Exception ex) {
            throw ex;
        }
        return retVat;
    }

    private HashMap<Integer, String> getLstThuTu(Vector<diengiai> lstDienGiai) throws Exception {
        HashMap<Integer, String> lstThuTu = new HashMap<Integer, String>();
        try {
            for (diengiai dg : lstDienGiai) {
                if (!lstThuTu.containsKey(dg.getThutusheet())) {
                    lstThuTu.put(dg.getThutusheet(), dg.getTendaydu());
                }
            }
        } catch (Exception ex) {
            throw ex;
        }
        return lstThuTu;
    }

    private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date date = new Date();
        return dateFormat.format(date);
    }

    private void copyFile(String from, String to) {
        try {
            File fFrom = new File(from);
            File fTo = new File(to);
            InputStream inStream = new FileInputStream(fFrom);
            OutputStream outStream = new FileOutputStream(fTo);
            byte[] buffer = new byte[1024];
            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            inStream.close();
            outStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
